<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Choice_model extends CI_Model {
	function get_by_id($choice_id) {
		$this->db->where('id', $choice_id);
		$this->db->where('status', DB_STATUS_NORMAL);
		$query = $this->db->get('choice');
		log_message('debug', $this->db->last_query());
		
		$count = $query->num_rows();
		return $count == 1 ? $query->row_array() : NULL;
	}
	
	function is_voted($choice_id, $user_id) {
		$this->db->where('choice_id', $choice_id);
		$this->db->where('user_id', $user_id);
		$this->db->where('status', DB_STATUS_NORMAL);
		$this->db->from('user_choice');
		log_message('debug', $this->db->last_query());
		
		return $this->db->count_all_results() >= 1;
	}
	
	function vote($choice_id, $user_id) {
		$this->db->trans_start();
		$this->db->where('id', $choice_id);
		$this->db->where('status', DB_STATUS_NORMAL);
		$query = $this->db->get('choice');
		log_message('debug', $this->db->last_query());
		
		$count = $query->num_rows();
		$choice = $count == 1 ? $query->row_array() : NULL;
		$this->db->insert('user_choice', array(
			'user_id' => $user_id,
			'post_id' => $choice['post_id'],
			'status' => DB_STATUS_NORMAL,
			'create_time' => date('Y-m-d H:i:s')
		));
		log_message('debug', $this->db->last_query());
		$this->db->where('id', $choice_id);
		$this->db->set('count', 'count+1', FALSE);
		$this->db->update('choice');
		$affected_rows = $this->db->affected_rows();
		$this->db->trans_complete();
		log_message('debug', $this->db->last_query());
		
		return $affected_rows;
	}
}